package pers.ree.demo.concurrent;

import java.util.concurrent.TimeUnit;

public class InterruptDemo {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try {
                while (!Thread.interrupted()) {
                    System.out.println("Working...");
                    TimeUnit.MILLISECONDS.sleep(500);
                }
            } catch (InterruptedException e) {
                boolean isInterrupted = Thread.currentThread().isInterrupted();
                System.out.println("Thread is interrupted during work! isInterrupted="+isInterrupted);
                Thread.currentThread().interrupt();
                isInterrupted = Thread.currentThread().isInterrupted();
                System.out.println("Thread is interrupted during work! after catch block interrupt executed, isInterrupted="+isInterrupted);
            } finally {
                System.out.println("Clean up resources...");
            }
        });

        t1.start();

        try {
            TimeUnit.MILLISECONDS.sleep(2000);
            t1.interrupt();
        } catch (InterruptedException e) {
            System.out.println("Thread is interrupted after start!");
            e.printStackTrace();
        }

        boolean isInterrupted = t1.isInterrupted();
        System.out.println("Main Thread end, isInterrupted="+isInterrupted);
    }
}
